# coding=UTF-8

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

from live_api.tools.Output_Helper import *
from live_api.tools.constant import datais
from live_api.tools.object_init import obj_init_user
from live_api.tools.Third_Netease_ServerAPI import ServerAPI
from live_api.tools.sms import verifycode
import live_api.tools.utils_file as ufile
import random,string


import types
from urllib import urlencode, urlopen
from live_api.tools.hashcompat import md5_constructor as md5

from django.shortcuts import render, redirect, HttpResponse
# from live_api.tools.utils import AliPay
import json
import time




# curl -d "aa=1&bb=2" http://127.0.0.1:8000/api/test1/
@csrf_exempt
def test1(request):
    msg = ""
    try:
        info = INFO(request)
        info.checkPostEmpty('aa', 'bb')
        msg += "aa=" + info.aa
        msg += "bb=" + info.bb
    except Exception, e:
        msg = str(e)
    return HttpResponse(msg)

@csrf_exempt
def user_regist(request):
    ret = ReturnJ()
    ret.id_user=''
    neteas_euser_info=''
    try:
        db =DB.getDB()
        info = INFO(request)
        info.checkPostEmpty('tel_number', 'cpwd', "identity_code")
        info.cdate = info.tick()  # 标准注册
        sql = sqlr("select * from user where tel_number=$tel_number", info)
        n, rows = db.query(sql)
        if n > 0:

            ret.code=1002
            ret.msg = "用户已注册!"
        else:
            data=verifycode(info.tel_number,info.identity_code)
            if data['code']==200:
                try:
                    info.id = maxid("user", "id")
                    salt = ''.join(random.sample(string.ascii_letters + string.digits, 6))
                    info.nickname = '%s%s' % (salt, info.id)
                    # 测试库网易云用户名
                    # neteas_euser_info=p.createUserId("liuhua_%s"% info.id,info.tel_number)
                    # 正式库网易云用户名
                    neteas_euser_info=p.createUserId("new_liuhua_%s"% info.id, info.nickname)
                    # print neteas_euser_info
                    if neteas_euser_info['code']==200:
                        info.accid=neteas_euser_info['info']['accid']
                        info.token=neteas_euser_info['info']['token']
                        try:

                            info.gender=2
                            info.ctype=0
                            info.address=''
                            info.img=datais.header
                            info.signature=''
                            info.share_code=''
                            info.par1=0
                            info.par2=''
                            info.is_used=1

                            info.cname=info.nickname
                            sql = sqlr(
                                    "insert into user(id,cname,tel_number,cpwd,ctype,accid,token,nickname,gender,address,img,signature,share_code,par1,par2,cdate,is_used) "
                                    "values($id,$cname,$tel_number,$cpwd,$ctype,$accid,$token,$nickname,$gender,$address,$img,$signature,$share_code,$par1,$par2,$cdate,$is_used)", info)
                            db.execute(sql)

                            # /**********************************创建用户的user_finance记录************************************************************/
                            info.id1 = maxid("user_finance", "id")
                            sql = sqlr(
                                "select id_user from user_finance where user_finance.id_user=$id",
                                info)
                            n, rows = db.query(sql)
                            if n == 0:
                                sql = sqlr(
                                    "insert into user_finance(id,id_user,pre_fmoney,total_rmb,total_fmoney,total_given) values($id1,$id,0,0,0,0)",
                                    info)
                                db.execute(sql)
                            # /**********************************************************************************************/
                            ret.code=200
                            ret.id_user=info.id
                            ret.msg = "注册成功!"
                        except Exception, e:
                            ret.code=1007
                            ret.msg = "数据库操作异常!"+str(e)
                    else:
                        # info.id = maxid("user", "id") + 2
                        n, res = db.query("select max(id) as maxid from user")
                        # print res
                        if res[0]['maxid']:
                            id = res[0]['maxid']
                            id_p = int(res[0]['maxid']) + 4
                            sql = "insert into user(id,cname,tel_number,cpwd,ctype,accid,token,nickname,gender,address,img,signature,share_code,par1,par2,cdate,is_used) values(%d, 'liuhua', '12345678901', '123456', '0', '111111', '11111', 'liuhua', 0, 'beijing','cms_liuhua/user/img1524225062.png', '0', '12342', '0', '0', '123456', 1)" % (
                                id_p)
                            # sql = "insert into user(id,cname,tel_number,cpwd,ctype,accid,token,nickname,gender,address,img,signature,share_code,par1,par2,cdate,is_used) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" % (id_p, 'liuhua', '12345678901', '123456', '0', '111111', '11111', 'liuhua', 0, 'beijing','cms_liuhua/user/img1524225062.png', '0', '12342', '0', '0', '123456', 1)
                            db.execute(sql)
                        # 测试库网易云用户名
                        # neteas_euser_info=p.createUserId("liuhua_%s"% info.id,info.tel_number)
                        # 正式库网易云用户名
                        # neteas_euser_info = p.createUserId("new_liuhua_%s" % info.id, info.tel_number)
                        # # print neteas_euser_info
                        # if neteas_euser_info['code'] == 200:
                        #     info.accid = neteas_euser_info['info']['accid']
                        #     info.token = neteas_euser_info['info']['token']
                        #     try:
                        #
                        #         info.gender = 2
                        #         info.ctype = 0
                        #         info.address = ''
                        #         info.img = datais.header
                        #         info.signature = ''
                        #         info.share_code = ''
                        #         info.par1 = ''
                        #         info.par2 = ''
                        #         info.is_used = 1
                        #         salt = ''.join(random.sample(string.ascii_letters + string.digits, 6))
                        #         info.nickname = '%s%s' % (salt, info.id)
                        #         info.cname = info.nickname
                        #         sql = sqlr(
                        #             "insert into user(id,cname,tel_number,cpwd,ctype,accid,token,nickname,gender,address,img,signature,share_code,par1,par2,cdate,is_used) "
                        #             "values($id,$cname,$tel_number,$cpwd,$ctype,$accid,$token,$nickname,$gender,$address,$img,$signature,$share_code,$par1,$par2,$cdate,$is_used)",
                        #             info)
                        #         db.execute(sql)
                        #
                        #         # /**********************************创建用户的user_finance记录************************************************************/
                        #         info.id1 = maxid("user_finance", "id")
                        #         sql = sqlr(
                        #             "select id_user from user_finance where user_finance.id_user=$id",
                        #             info)
                        #         n, rows = db.query(sql)
                        #         if n == 0:
                        #             sql = sqlr(
                        #                 "insert into user_finance(id,id_user,pre_fmoney,total_rmb,total_fmoney,total_given) values($id1,$id,0,0,0,0)",
                        #                 info)
                        #             db.execute(sql)
                        #         # /**********************************************************************************************/
                        #         ret.code = 200
                        #         ret.id_user = info.id
                        #         ret.msg = "注册成功!"
                        #     except Exception, e:
                        #         ret.code = 1007
                        #         ret.msg = "数据库操作异常!" + str(e)

                        ret.code=neteas_euser_info['code']
                        ret.msg = "服务器繁忙，请稍后在试!"
                        # print '1',"服务器繁忙，请稍后在试!"
                except Exception, e:
                    n, res = db.query("select max(id) as maxid from user")
                    # print res
                    if res[0]['maxid']:
                        id = res[0]['maxid']
                        id_p = int(res[0]['maxid']) + 4
                        sql = "insert into user(id,cname,tel_number,cpwd,ctype,accid,token,nickname,gender,address,img,signature,share_code,par1,par2,cdate,is_used) values(%d, 'liuhua', '12345678901', '123456', '0', '111111', '11111', 'liuhua', 0, 'beijing','cms_liuhua/user/img1524225062.png', '0', '12342', '0', '0', '123456', 1)" % (id_p)

                        # sql ="insert into user(id,cname,tel_number,cpwd,ctype,accid,token,nickname,gender,address,img,signature,share_code,par1,par2,cdate,is_used) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" % (id_p,'liuhua', '12345678901','123456','0','111111','11111','liuhua',0,'beijing','cms_liuhua/user/img1524225062.png','0','12342','0','0','123456',1)
                        db.execute(sql)
                    ret.code=1006
                    # ret.msg = "使用网易云信异常!"+str(e)
                    ret.msg = "服务器繁忙，请稍后在试!"

                    # print '2',"使用网易云信异常!"+str(e)
            else:
                ret.code=1003
                ret.msg = "验证码错误!"
    except Exception, e:
        # print(str(e))
        ret.code = 1010
        ret.msg = str(e)

    return HttpResponse(ret.toJson())

import hashlib
@csrf_exempt
def user_login(request):
    ret = ReturnJ()
    ret.id_user=''
    try:
        # print 111111111111
        db =DB.getDB()
        info = INFO(request)
        info.checkPostEmpty('cpwd', "ctype")

        #info.checkPostEmpty('cname','tel_number', 'cpwd', "ctype")
        if int(info.ctype) == 0:
            info.checkPostEmpty('tel_number')
            # print info.tel_number
            sql = sqlr("select * from user where tel_number=$tel_number", info)
            # print sql
            try:
                n, rows = db.query(sql)
                if n > 0:
                    str1 = str(info.cpwd)
                    hl = hashlib.md5()
                    hl.update(str1.encode(encoding='utf-8'))
                    pwd = hl.hexdigest()
                    if rows[0]['cpwd']==info.cpwd or rows[0]['cpwd'] == pwd:
                        ret.code=200
                        ret.msg = "请求成功!"
                        ret.id_user = rows[0]['id']
                    else:
                        ret.code=1004
                        ret.msg = "密码错误!"
                else:
                    ret.code=1001
                    ret.msg = "用户不存在!"
            except Exception, e:
                # print(str(e))
                ret.code=1007
                ret.msg = "数据库操作异常!"+str(e)
        else:# 第三方登录
            info.checkPostEmpty('cname','gender','nickname','img')
            sql = sqlr("select * from user where cname=$cname", info)
            n, rows = db.query(sql)
            id_user=''
            if n > 0:
                if rows[0]['cpwd']==info.cpwd:
                    pass
                else:
                    # info.id = maxid("user", "id")
                    sql = sqlr("update user set cpwd=$cpwd where cname=$cname", info)
                    db.execute(sql)
                id_user=rows[0]['id']
                ret.id_user = id_user
                ret.code=200
                ret.msg = "请求成功!"
            else:
                info.cdate = info.tick()
                # 调用七牛上传图片
                # ret_img = ufile.upload(request, 'img', 'cms_liuhua/user/')
                # if ret_img != None and ret_img['data'] != None:
                #     info.img = ret_img['db_img_path']
                # else:
                #     info.img=datais.header

                try:
                    #到网易云信注册ID
                    info.id = maxid("user", "id")

                    # print info.img
                    # return HttpResponse(ret.toJson())
                    # 测试库
                    # neteas_euser_info=p.createUserId("liuhua_%s"% info.id,name=info.nickname,icon=info.img)
                    # 正式库
                    neteas_euser_info=p.createUserId("new_liuhua_%s"% info.id,name=info.nickname,icon=info.img)
                    if neteas_euser_info['code']==200:
                        info.accid=neteas_euser_info['info']['accid']
                        info.token=neteas_euser_info['info']['token']
                        try:
                            info.tel_number=''
                            info.ctype=info.ctype
                            info.address=''
                            info.signature=''
                            info.share_code=''
                            info.par1=''
                            info.par2=''
                            info.is_used=1
                            if info.img == '':
                                info.img = datais.header
                            else:
                                info.img = info.img[len(datais.url_img):]
                            sql = sqlr(
                                "insert into user(id,cname,tel_number,cpwd,ctype,accid,token,nickname,gender,address,img,signature,share_code,par1,par2,cdate,is_used) "
                                "values($id,$cname,$tel_number,$cpwd,$ctype,$accid,$token,$nickname,$gender,$address,$img,$signature,$share_code,$par1,$par2,$cdate,$is_used)", info)
                            db.execute(sql)
                            # /**********************************创建用户的user_finance记录************************************************************/
                            info.id1 = maxid("user_finance", "id")
                            sql = sqlr(
                                "select id_user from user_finance where user_finance.id_user=$id",
                                info)
                            n, rows = db.query(sql)
                            if n == 0:
                                sql = sqlr(
                                    "insert into user_finance(id,id_user,pre_fmoney,total_rmb,total_fmoney,total_given) values($id1,$id,0,0,0,0)",
                                    info)
                                db.execute(sql)
                            # /**********************************************************************************************/



                            id_user=info.id
                            ret.id_user = id_user
                            ret.code=200
                            ret.msg = "请求成功!"
                        except Exception, e:
                            # print(str(e))
                            ret.code=1007
                            ret.msg = "数据库操作异常!"+neteas_euser_info
                    else:
                        n, res = db.query("select max(id) as maxid from user")
                        # print res
                        if res[0]['maxid']:
                            id = res[0]['maxid']
                            id_p = int(res[0]['maxid']) + 4
                            sql = "insert into user(id,cname,tel_number,cpwd,ctype,accid,token,nickname,gender,address,img,signature,share_code,par1,par2,cdate,is_used) values(%d, 'liuhua', '12345678901', '123456', '0', '111111', '11111', 'liuhua', 0, 'beijing','cms_liuhua/user/img1524225062.png', '0', '12342', '0', '0', '123456', 1)" % (
                                id_p)

                            # sql = "insert into user(id,cname,tel_number,cpwd,ctype,accid,token,nickname,gender,address,img,signature,share_code,par1,par2,cdate,is_used) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" % (id_p, 'liuhua', '12345678901', '123456', '0', '111111', '11111', 'liuhua', 0, 'beijing','cms_liuhua/user/img1524225062.png', '0', '12342', '0', '0', '123456', 1)
                            db.execute(sql)
                        # info.id = maxid("user", "id") + 2
                        #
                        # # print info.img
                        # # return HttpResponse(ret.toJson())
                        # # 测试库
                        # # neteas_euser_info=p.createUserId("liuhua_%s"% info.id,name=info.nickname,icon=info.img)
                        # # 正式库
                        # neteas_euser_info = p.createUserId("new_liuhua_%s" % info.id, name=info.nickname, icon=info.img)
                        # if neteas_euser_info['code'] == 200:
                        #     info.accid = neteas_euser_info['info']['accid']
                        #     info.token = neteas_euser_info['info']['token']
                        #     try:
                        #         info.tel_number = ''
                        #         info.ctype = 1
                        #         info.address = ''
                        #         info.signature = ''
                        #         info.share_code = ''
                        #         info.par1 = ''
                        #         info.par2 = ''
                        #         info.is_used = 1
                        #         if info.img == '':
                        #             info.img = datais.header
                        #         else:
                        #             info.img = info.img[len(datais.url_img):]
                        #         sql = sqlr(
                        #             "insert into user(id,cname,tel_number,cpwd,ctype,accid,token,nickname,gender,address,img,signature,share_code,par1,par2,cdate,is_used) "
                        #             "values($id,$cname,$tel_number,$cpwd,$ctype,$accid,$token,$nickname,$gender,$address,$img,$signature,$share_code,$par1,$par2,$cdate,$is_used)",
                        #             info)
                        #         db.execute(sql)
                        #         # /**********************************创建用户的user_finance记录************************************************************/
                        #         info.id1 = maxid("user_finance", "id")
                        #         sql = sqlr(
                        #             "select id_user from user_finance where user_finance.id_user=$id",
                        #             info)
                        #         n, rows = db.query(sql)
                        #         if n == 0:
                        #             sql = sqlr(
                        #                 "insert into user_finance(id,id_user,pre_fmoney,total_rmb,total_fmoney,total_given) values($id1,$id,0,0,0,0)",
                        #                 info)
                        #             db.execute(sql)
                        #         # /**********************************************************************************************/
                        #
                        #         id_user = info.id
                        #         ret.id_user = id_user
                        #         ret.code = 200
                        #         ret.msg = "请求成功!"
                        #     except Exception, e:
                        #         # print(str(e))
                        #         ret.code = 1007
                        #         ret.msg = "数据库操作异常!" + neteas_euser_info
                        # ret.code=1006
                        # ret.msg = "使用网易云信+++++++++异常!"+str(neteas_euser_info)

                except Exception, e:
                    n, res = db.query("select max(id) as maxid from user")
                    # print res
                    if res[0]['maxid']:
                        id = res[0]['maxid']
                        id_p = int(res[0]['maxid']) + 4
                        # sql = "insert into user(id,cname,tel_number,cpwd,ctype,accid,token,nickname,gender,address,img,signature,share_code,par1,par2,cdate,is_used) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" % (id_p, 'liuhua', '12345678901', '123456', '0', '111111', '11111', 'liuhua', 0, 'beijing','cms_liuhua/user/img1524225062.png', '0', '12342', '0', '0', '123456', 1)
                        sql = "insert into user(id,cname,tel_number,cpwd,ctype,accid,token,nickname,gender,address,img,signature,share_code,par1,par2,cdate,is_used) values(%d, 'liuhua', '12345678901', '123456', '0', '111111', '11111', 'liuhua', 0, 'beijing','cms_liuhua/user/img1524225062.png', '0', '12342', '0', '0', '123456', 1)" % (id_p)
                        db.execute(sql)
                    ret.code=1006
                    ret.msg = "服务器繁忙，请稍后在试!"

                    # ret.msg = "使用网易云信异常!"+str(e)
    except Exception, e:
        # print(str(e))
        ret.code = 1010
        ret.msg = str(e)
    res = HttpResponse(ret.toJson())
    res["Access-Control-Allow-Origin"] = "*"
    res["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
    res["Access-Control-Max-Age"] = "1000"
    res["Access-Control-Allow-Headers"] = "*"
    return res



#热门列表
@csrf_exempt
def hotlist(request):
    ret = ReturnJ()
    try:
        db =DB.getDB()
        info = INFO(request)
        info.checkPostEmpty('cur_page', 'pagesize')

        # 已经查询的总条目数
        beRequestedSize = int(info.cur_page) * int(info.pagesize)
        # print 111111111111111111111,beRequestedSize
        # 直播所有条数
        n_all_live,all_live_rows = db.query("select * from video where ctype=0")
        # print 222222222222222222222,n_all_live
        # 查询到的直播条目
        liven = 0
        liverows = []
        # 如果已经查询条目数小于直播条目数，那么直播还没查完,本页仍需去查询直播条目
        if beRequestedSize < n_all_live:
            sql = "select * from video  where ctype=0 and par1=0 order by ncustomer desc limit %s,%s" % (beRequestedSize,info.pagesize)
            liven,liverows = db.query(sql)
        # print liven
        videon, videorows = 0,[]
        # 如果查询的直播数不足一页，需要去查询回放条目
        # print 3333333333,info.pagesize
        # print 777777777777,liven
        if liven < int(info.pagesize):

            #  回放查询起始条目
            video_start = 0
            # print 10000000000000,beRequestedSize # 已经查询的总条目数
            # print 4444444444444,n_all_live # 直播所有条数
            # if beRequestedSize - n_all_live > 0:
            # if beRequestedSize - n_all_live < 0:
            if beRequestedSize - n_all_live > 0:
                video_start = beRequestedSize - n_all_live
            else:
                video_start = beRequestedSize

            # 需要查询的回放条数，需要去掉当页已查询的直播数
            needVideo = int(info.pagesize) - liven
            sql = "select * from video  where ctype=1 order by end_date desc limit %s,%s" % (video_start, needVideo)
            print sql
            videon, videorows = db.query(sql)

        rows = []
        if liven > 0:
            rows.extend(liverows)
        if videon > 0:
            rows.extend(videorows)


        # sql = sqlr("select * from video order by ctype asc,ncustomer desc,nlooked desc limit #cur_page,#pagesize",
        #            info)
        # n, rows = db.query(sql)
        ret.hotlist = out_farmat_video(rows,1)

    except Exception, e:
        ret.code = 1010
        ret.msg = str(e)
        # print(str(e))

    return HttpResponse(ret.toJson())


#最新列表
@csrf_exempt
def lastestlist(request):
    ret = ReturnJ()
    try:
        db =DB.getDB()
        # sql = 'select * from python_web.Choice_question where id=1'
        # n, rows = db.query(sql)
        info = INFO(request)
        info.checkPostEmpty('cur_page', 'pagesize')
        info.cur_page = str(int(info.cur_page) * int(info.pagesize))
        sql = sqlr("select * from video where par1=0 order by ctype asc,start_date desc limit #cur_page,#pagesize", info)
        n, rows = db.query(sql)
        # print type(rows[0]['tilte'])
        ret.lastestlist = out_farmat_video(rows,1)

    except Exception, e:
        ret.code = 1010
        ret.msg = str(e)
        # print(str(e))

    res = HttpResponse(ret.toJson())
    res["Access-Control-Allow-Origin"] = "*"
    res["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
    res["Access-Control-Max-Age"] = "1000"
    res["Access-Control-Allow-Headers"] = "*"
    return res


@csrf_exempt
def lastestlist_share(request):
    ret = ReturnJ()
    try:
        db =DB.getDB()
        info = INFO(request)
        info.checkPostEmpty('cur_page', 'pagesize')
        info.cur_page = str(int(info.cur_page) * int(info.pagesize))
        sql = sqlr("select * from video where par1=0 and ctype=1 order by ctype asc,start_date desc limit #cur_page,#pagesize", info)
        n, rows = db.query(sql)
        ret.lastestlist = out_farmat_video(rows,1)

    except Exception, e:
        ret.code = 1010
        ret.msg = str(e)
        # print(str(e))

    res = HttpResponse(ret.toJson())
    res["Access-Control-Allow-Origin"] = "*"
    res["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
    res["Access-Control-Max-Age"] = "1000"
    res["Access-Control-Allow-Headers"] = "*"
    return res








 #
@csrf_exempt
def zone(request,id):
    ret = ReturnJ()
    try:
        db =DB.getDB()
        info = INFO(request)
        info.id=id
        sql = sqlr("select * from zone_node where id_zone=$id", info)
        n, rows = db.query(sql)
        ret.zone = out_farmat_zone_node(rows)

    except Exception, e:
        ret.code = 1010
        ret.msg = str(e)
        # print(str(e))

    return HttpResponse(ret.toJson())


 #
@csrf_exempt
def page(request):
    ret = ReturnJ()
    try:
        # print type(datais.zone)
        zone = '[{"ctype":"0","id_zone":"1"},{"ctype":"1","id_zone":"2"},{"ctype":"2","id_zone":"3"}]'
        # print type(str(zone))
        ret.page = json.loads(zone)
    except Exception, e:
        ret.code = 1010
        ret.msg = str(e)
        # print(str(e))

    return HttpResponse(ret.toJson())

#主播热度排行
@csrf_exempt
def rank_actor_hot(request):
    ret = ReturnJ()
    try:
        db =DB.getDB()
        info = INFO(request)
        info.checkPostEmpty('cur_page', 'pagesize','id_user')
        # info.id=id
        info.cur_page = str(int(info.cur_page) * int(info.pagesize))
        sql = sqlr("SELECT user.*,npraise.n_praise from user INNER JOIN (select * from user_count WHERE id_user in(SELECT id from actor) ORDER BY n_praise DESC) as npraise on user.id=npraise.id_user limit #cur_page,#pagesize", info)
        # print sql
        n, rows = db.query(sql)
        ret.rank_actor_hot = out_farmat_users(rows,id=info.id_user)

    except Exception, e:
        ret.code = 1010
        ret.msg = str(e)
        # print(str(e))

    return HttpResponse(ret.toJson())


#主播人气排行
@csrf_exempt
def rank_actor_fans(request):
    ret = ReturnJ()
    try:
        db =DB.getDB()
        info = INFO(request)
        info.checkPostEmpty('cur_page', 'pagesize','id_user')
        # info.id=info.id_user
        info.cur_page = str(int(info.cur_page) * int(info.pagesize))
        sql = sqlr("SELECT user.*,fan_s.n_fans from  user INNER join (select * from user_count WHERE id_user in(SELECT id from actor) ORDER BY n_fans DESC) as fan_s  on fan_s.id_user=user.id limit #cur_page,#pagesize", info)
        n, rows = db.query(sql)
        ret.rank_actor_fans = out_farmat_users(rows,id=info.id_user)

    except Exception, e:
        ret.code = 1010
        ret.msg = str(e)
        # print(str(e))

    return HttpResponse(ret.toJson())




#直播热度排行  **************************************
@csrf_exempt
def rank_room(request):
    ret = ReturnJ()
    try:
        db =DB.getDB()
        info = INFO(request)
        # info.id=id
        info.cur_page = str(int(info.cur_page) * int(info.pagesize))
        # sql = sqlr("select * from user where user.id in (select id_user from user_count order by n_payattention desc ) limit #cur_page,#pagesize", info)
        sql = sqlr("select * from video where ctype=0 and par1=0 order by nlooked DESC limit #cur_page,#pagesize", info)
        # print sql
        n, rows = db.query(sql)
        # print n
        ret.video_user = out_farmat_video(rows)
        # ret.video = rows
    except Exception, e:
        ret.code = 1010
        ret.msg = str(e)
        # print(str(e))

    return HttpResponse(ret.toJson())


#获取热门搜索关键字
@csrf_exempt
def keywords(request):
    ret = ReturnJ()
    try:
        db =DB.getDB()
        info = INFO(request)
        sql = sqlr("select * from keywords",info)
        n, rows = db.query(sql)
        ret.keywords = out_farmat('keywords',rows)

    except Exception, e:
        ret.code = 1010
        ret.msg = str(e)
        # print(str(e))

    return HttpResponse(ret.toJson())


#搜索
@csrf_exempt
def search(request):
    ret = ReturnJ()
    try:
        db =DB.getDB()
        info = INFO(request)
        info.checkPostEmpty('words','id_user')
        sql = "select user.*,user_count.n_fans,user_count.n_payattention from user left join user_count on user.id=id_user where user.nickname like '%"+info.words+"%'  "
        n, rows = db.query(sql)
        ret.actor = out_farmat_users(rows,1,id=info.id_user)

        sql = "select * from video where cname like '%"+info.words+"%' "
        n, rows = db.query(sql)
        ret.video = out_farmat_video(rows,1)

    except Exception, e:

        ret.code = 1010
        ret.msg = str(e)
        # print(str(e))

    return HttpResponse(ret.toJson())


#花费
@csrf_exempt
def rank_spend(request):
    ret = ReturnJ()
    try:
        db =DB.getDB()
        info = INFO(request)
        info.checkPostEmpty('cur_page', 'pagesize','id_actor','id_my')
        info.cur_page = str(int(info.cur_page) * int(info.pagesize))
        sql = sqlr("SELECT user.*,sum(gift_fmoney) AS 'spend' FROM user_consume,user WHERE user_consume.id_user_receive=#id_actor AND user.id=user_consume.id_user_send GROUP BY id_user_send ORDER BY sum(gift_fmoney)DESC limit #cur_page,#pagesize",info)
        n,rows = db.query(sql)
        for row in rows:
            row['spend'] = str(row['spend'])

        # print rows
        # print rows
        ret.rank_spend = out_farmat_users(rows,id=info.id_my)
    except Exception, e:
        ret.code = 1010
        ret.msg = str(e)
        # print(str(e))

    res = HttpResponse(ret.toJson())
    res["Access-Control-Allow-Origin"] = "*"
    res["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
    res["Access-Control-Max-Age"] = "1000"
    res["Access-Control-Allow-Headers"] = "*"
    return res


# 举报
@csrf_exempt
def user_complain(request):
    ret = ReturnJ()
    try:
        db = DB.getDB()
        info = INFO(request)
        info.id = maxid("user_complain", "id")
        info.checkPostEmpty('anchor_id','user_id',"vido_id","complain_type")
        info.detail = out_farmat_detail(int(info.complain_type))
        info.cdate = info.tick()  # 投诉时间
        sql = sqlr(
            "insert into user_complain(id,id_actor,id_user,id_video,type,detail,cdate)"
            "values($id,$anchor_id,$user_id,$vido_id,$complain_type,$detail,$cdate)",info)
        db.execute(sql)
        ret.code = 200
        ret.type = info.detail
        ret.msg = "举报成功!"
    except Exception, e:
        ret.code = 1010
        ret.msg = str(e)
        # print(str(e))
    # print ('test---->', ret.toJson())
    # print(type(ret.toJson()))
    return HttpResponse(ret.toJson())

# 支付
# 确认支付
#     完成1
from alipay import AliPay
from django.conf import settings

notify_url = "http://123.139.46.17:8003/api/aliapy_back_url/"
@csrf_exempt
def ali():
    merchant_private_key_path = settings.BASE_DIR + '/live_api/static/keys/pri/pri.pem' #设置公钥和私钥的地址，文件上下两行begin和end是必须的，公钥就放在第二行。
    alipay_public_key_path = settings.BASE_DIR + '/live_api/static/keys/pub/pub.pem'
    app_private_key_string = open(merchant_private_key_path).read()
    alipay_public_key_string = open(alipay_public_key_path).read()
    app_id = "2017032806447490" #复制来自支付宝生成的id

    alipay = AliPay(
        appid=app_id,
        app_notify_url=notify_url,  # 默认回调url
        app_private_key_string=app_private_key_string,
        alipay_public_key_string=alipay_public_key_string,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
        sign_type="RSA",  # RSA 或者 RSA2
        debug = False  # 默认False
    )
    return alipay

@csrf_exempt
def recharge(request):
    ret = ReturnJ()
    db = DB.getDB()
    alipay = ali()
    try:
        info = INFO(request)
        info.checkPostEmpty('user_id', 'money')
        back_url_user_id = info.user_id
        info.order_type = 0
        id_order = "LB" + str(int(round(time.time())))
        info.create_time = str(int(round(time.time())))
        info.id_order = id_order
        money = int(info.money)
        order_string = alipay.api_alipay_trade_app_pay(
                out_trade_no=id_order,  # 商户订单号
                total_amount=money,
                subject="榴花币",  # 商品简单描述
                notify_url=notify_url # 可选, 不填则使用默认notify url
            )
        sql = sqlr(
            "insert into pay_order(id_user,money,id_order,order_type,create_time)"
            "values($user_id,$money,$id_order,$order_type,$create_time)", info)
        db.execute(sql)
        ret.code = 200
        ret.type = info.money
        ret.query_params = str(order_string)
        # print order_string
        # ret.query_params = pay_url
        ret.msg = "充值码!"
        # return redirect(pay_url)
    except Exception, e:
        ret.code = 1010
        ret.msg = str(e)
        # print(str(e))
    # print('test------>', ret.toJson())
    return HttpResponse(ret.toJson())


@csrf_exempt
def aliapy_back_url(request):
    alipay = ali()
    info = INFO(request)
    db = DB.getDB()
    if request.method == "POST":
        # 检测是否支付成功
        # 去请求体中获取所有返回的数据：状态/订单号
        from urlparse import parse_qs

        # request.body                  => 字节类型
        # request.body.decode('utf-8')  => 字符串类型
        """
        {"k1":["v1"],"k2":["v1"]}
        k1=[v1]&k2=[v2]
        """
        body_str = request.body.decode('utf-8')
        post_data = parse_qs(body_str)
        # {k1:[v1,],k2:[v2,]}

        # {k1:v1}
        post_dict = {}
        for k, v in post_data.items():
            post_dict[k] = v[0]
        sign = post_dict.pop('sign',None)
        if post_dict['trade_status']:
            info.order_status = 1  # 支付类型

            info.pay_time = str(int(round(time.time())))  # 支付时间
            info.out_trade_no = post_dict['out_trade_no']  # 订单号
            info.trade_no = post_dict['trade_no']  # 支付宝订单号  alipay_order
            # print type(post_dict['buyer_pay_amount'])
            money = post_dict['buyer_pay_amount']
            srt_money = filter(str.isdigit, money.encode("utf-8"))[:1]
            int_money = int(srt_money)
            # info.money = int(post_dict['buyer_pay_amount'] * 10)
            info.money =int_money * 10
            # /********************************************************************************************************************/
            info.id = maxid("user_finance", "id")
            # 判断用户是否为空，如果为空就不插入数据
            sql = sqlr("select id_user from pay_order where id_order=$out_trade_no", info)
            n2, rows = db.query(sql)
            # 判断用户是否存在，不存在则创建
            sql = sqlr("select id_user from user_finance where user_finance.id_user=(select id_user from pay_order where id_order=$out_trade_no)", info)
            n, rows = db.query(sql)
            if n2 != 0:
                if n == 0:
                    sql = sqlr("insert into user_finance(id,id_user,pre_fmoney,total_rmb,total_fmoney,total_given) values($id,(select id_user from pay_order where id_order=$out_trade_no),0,0,0,0)",info)
                    db.execute(sql)
            #/*****************************************************************************************************************/
            sql = sqlr("select order_status from pay_order where id_order=$out_trade_no", info)
            n, rows = db.query(sql)
            # print rows['order_status']
            if rows[0]['order_status'] == 0:
                sql = sqlr("update pay_order set pay_time=$pay_time ,alipay_order=$trade_no ,order_status=$order_status where id_order=$out_trade_no", info)
                # sq2 = "update user_finance set pre_fmoney=pre_fmoney+%f where id_user=(select id_user from pay_order where alipay_order='%s')" %(info.money,info.trade_no)
                sq2 = "update user_finance set pre_fmoney=pre_fmoney+%d where id_user=(select id_user from pay_order where alipay_order='%s')" %(info.money,info.trade_no)
                # sq2 = sqlr("update user_finance set pre_fmoney=12 where id_user=217", info)
                # print sql
                # print sq2
                db.execute(sql)
                db.execute(sq2)
        return HttpResponse('success')
    else:
        params = request.GET.dict()
        sign = params.pop('sign', None)
        status = alipay.verify(params, sign)
        # print('GET验证', status)
        return HttpResponse('success')

@csrf_exempt
def withdraw_cash(request):
    ret = ReturnJ()
    db = DB.getDB()
    try:
        info = INFO(request)
        info.checkPostEmpty("money","id_user",'id_account','real_name')
        info.user = int(info.id_user)
        info.account = str(info.id_account)
        info.id = maxid("user_getcash", "id")
        info.state = 0
        info.money = float(info.money)
        # print info.money
        info.take_fmoney = info.money*10

        # /**************************************************/
        sql = ("update user_finance set pre_fmoney=pre_fmoney-%d where id_user=%s"%(info.take_fmoney,info.user))
        # print sql
        db.execute(sql)
        # /**************************************************/
        sql = sqlr("update user set id_account=$account, real_name=$real_name where id=$user", info)
        db.execute(sql)

        info.cdate = int(time.time())
        # print type(info.cdate), type(info.state),type(info.take_fmoney), type(info.id_account),type(info.real_name),
        sql = sqlr("insert into user_getcash(id,id_actor,take_fmoney,take_rmb,state,cdate,id_account,real_name) values($id,$user,$take_fmoney,$money,$state,$cdate,$account,$real_name)",info)
        # print sql
        db.execute(sql)
        ret.code = 200
        ret.msg = "成功提现!"

    except Exception, e:
        ret.code = 1010
        ret.msg = str(e)
    return HttpResponse(ret.toJson())


@csrf_exempt
def buy_gift(request):
    ret = ReturnJ()
    db = DB.getDB()
    try:
        # print 1111111111111111111111111111111111111111111
        info = INFO(request)
        info.checkPostEmpty("id_sender","lh_coins",'id_gift','gift_num',"id_receiver")
        # print info.id_sender,info.lh_coins,info.id_gift,info.gift_num,info.id_receiver
        info.pre_fmoney = int(info.lh_coins) # 虚拟币值
        # print info.pre_fmoney
        info.money = float(int(info.pre_fmoney)/10.0)  # 现金
        # print info.money
        # 送礼物人
        # print 1111111111111111111111111111111111111111111
        # sql = sqlr("update user_finance set pre_fmoney=pre_fmoney-$pre_fmoney ,total_rmb=total_rmb+$money, total_fmoney=total_fmoney+$pre_fmoney where id_user=$id_sender", info)
        sql = ("update user_finance set pre_fmoney=pre_fmoney-%d ,total_rmb=total_rmb+%.2f, total_fmoney=total_fmoney+%d where id_user=%s"%(info.pre_fmoney,info.money,info.pre_fmoney,info.id_sender))
        db.execute(sql)
        # 接受礼物的主播
        # sql = sqlr("update user_finance set pre_fmoney=pre_fmoney+$pre_fmoney, total_given=total_given+$pre_fmoney where id_user=$id_receiver",info)
        sql = ("update user_finance set pre_fmoney=pre_fmoney+%d, total_given=total_given+%d where id_user=%s"%(info.pre_fmoney,info.pre_fmoney,info.id_receiver))
        db.execute(sql)
        # 送礼记录
        info.id = maxid("user_consume", "id")
        info.cdate = int(time.time())
        # sql = sqlr(
        #     "insert into user_consume(id,id_user_send,id_user_receive,id_gift,gift_fmoney,cdate) "
        #     "values($id,$id_sender,$id_receiver,$id_gift,$pre_fmoney,$cdate)",
        #     info)
        sql = (
            "insert into user_consume(id,id_user_send,id_user_receive,id_gift,gift_fmoney,cdate) "
            "values(%s,%s,%s,%s,%s,%s)"%(info.id,info.id_sender,info.id_receiver,info.id_gift,info.pre_fmoney,info.cdate))
        db.execute(sql)

        sql = sqlr("select pre_fmoney from user_finance where id_user=$id_sender", info)
        n, rows = db.query(sql)

        ret.pre_fmoney =rows[0]['pre_fmoney']
        ret.code = 200
        ret.msg = "送礼物成功!"

    except Exception, e:
        ret.code = 1010
        ret.msg = str(e)
    return HttpResponse(ret.toJson())


from django.http import HttpResponse, HttpResponseRedirect
import  json
import httplib

@csrf_exempt
def iap_pay(request):

    ret = ReturnJ()
    db = DB.getDB()
    info = INFO(request)
    # uid = request.uid
    info.checkPostEmpty('productId','Recharge_amount','user_id',"transactionId",'receipt_data',"sandbox")
    jsonStr = json.dumps({"receipt-data": info.receipt_data})
    sql = sqlr("select * from iap_validation where transactionId=$transactionId",info)
    n,row = db.query(sql)
    if n>0:
        ret.code=300
        ret.msg='订单重复'
    else:
        sql = sqlr("insert into iap_validation(transactionId) values($transactionId)", info)
        db.execute(sql)
        # sandbox
        # https: // buy.itunes.apple.com / verifyReceipt
        try:
            if info.sandbox == 0:
                connect = httplib.HTTPSConnection("buy.itunes.apple.com")
            else:
                connect = httplib.HTTPSConnection("sandbox.itunes.apple.com")
            headers = {"Content-type": "application/json"}
            connect.request("POST", "/verifyReceipt", jsonStr)
            result = connect.getresponse()
            data = result.read()
            connect.close()
            decodedJson = json.loads(data)
            # print decodedJson
            status = decodedJson[u'status']
            # info.original_transaction_id = decodedJson[u'receipt'][u'original_transaction_id'][u'original_transaction_id']
            info.transaction_id = decodedJson[u'receipt'][u'in_app'][0][u'transaction_id']
            if status==0:
                sql = sqlr("select * from iap_validation where transactionId=$transaction_id", info)
                n, rows = db.query(sql)
                if n>0:
                    info.status = 1
                    info.order_type = 2
                    info.pay_time = info.tick()
                    sql = sqlr("insert into pay_order(id_user,id_order,order_status,order_type,money,create_time,pay_time)"
                               "values($user_id,$transactionId,$status,$order_type,$Recharge_amount,$pay_time,$pay_time)", info)
                    db.execute(sql)
                    if info.Recharge_amount == '6':
                        info.pre_fmoney = 42
                    if info.Recharge_amount == "18":
                        info.pre_fmoney = 126
                    if info.Recharge_amount == "30":
                        info.pre_fmoney = 210
                    if info.Recharge_amount == "108":
                        info.pre_fmoney = 756
                    if info.Recharge_amount == "518":
                        info.pre_fmoney = 3626
                    # sql = sqlr("select pre_fmoney from user_finance where pre_fmoney=$pre_fmoney", info)
                    # n, rows = db.query(sql)
                    # info.pre_fmoney = float(rows[0]['pre_fmoney'])+float(info.pre_fmoney)
                    # print info.pre_fmoney
                    sql = "update user_finance set pre_fmoney=pre_fmoney+%d, total_given=0 where id_user=%s" % (info.pre_fmoney,info.user_id)
                    db.execute(sql)
                    sql = sqlr("select pre_fmoney from user_finance where id_user=$user_id", info)
                    n, rows = db.query(sql)
            ret.code = 200
            ret.pre_fmoney = rows[0]['pre_fmoney']

            ret.msg = '测试成功'
        except:
            ret.code = 404
            ret.msg = '测试失败'
    return HttpResponse(ret.toJson())

@csrf_exempt
def advertising(request):
    ret = ReturnJ()
    db = DB.getDB()
    try:
        sql = 'select * from advertising where status=0'
        n, rows = db.query(sql)
        if n > 0:
            import random
            row = random.sample(rows, 1)
            row[0].pop('createtime')
            row[0].pop('take_effect')
            ret.code = 200
            ret.msg = '获取广告图'
            ret.advertising = row
        else:
            row = [{"status": 1}]
            ret.msg = '广告全部过期'
            ret.code = 200
            ret.advertising = row
    except:
        ret.code = 404
        ret.msg = '获取版本信息失败'
    return HttpResponse(ret.toJson())


@csrf_exempt
def Versions(request):
    ret = ReturnJ()
    db = DB.getDB()
    info = INFO(request)
    info.checkPostEmpty('Versions', 'phone_system')
    try:
        if int(info.phone_system) == 0:
            phone_sys = 'Android'
        else:
            phone_sys = 'iPhone'
        res = {}
        l = []
        sql = "select * from versions where phone_system='%s' and cstatus=1 order by createtime asc" % phone_sys
        n, rows = db.query(sql)
        res['versions'] = rows[-1]['versions']
        res['update'] = rows[-1]['update_bool']
        # res['versions'] = '2.0.1'
        res['Download_url'] = 'http://applhzb.xiancity.cn:82/apk/android/LiuhuaAliveNew.apk'
        ret.info = res
        ret.msg = '获取版本信息成功'
        ret.code = 200
    except:
        ret.code = 404
        ret.msg = '获取版本信息失败'
    return HttpResponse(ret.toJson())


@csrf_exempt
def advertising_count(request):
    ret = ReturnJ()
    db = DB.getDB()
    info = INFO(request)
    info.checkPostEmpty('advertising_id')
    id = info.advertising_id
    try:
        sql = sqlk('update advertising set counts=counts+1 where id=#id',id=id)
        db.execute(sql)
        ret.msg = '统计增加一次'
        ret.code = 200
    except:
        ret.code = 404
        ret.msg = '统计失败'
    return HttpResponse(ret.toJson())

